﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS.DAL.Providers;
using SMS.DAL;

namespace SMS.Business.Items
{
    public class ItemBusiness : BusinessBase<Item,ItemSearchCriteria>
    {
        private ItemProvider itemProvider;
        private StockItemsProvider stockItemsProvider;

        public ItemBusiness()
        {
            itemProvider = new ItemProvider();
            stockItemsProvider = new StockItemsProvider();
        }

        public override bool Insert(Item item)
        {
            throw new NotImplementedException();
        }

        public bool Insert(Item item,StockItem stockItem)
        {
            ItemSearchCriteria ItemSearch = new ItemSearchCriteria()
            {
                Barcode = item.BarCode,
                Name = item.Name,
                Mark = item.Mark
            };

            var ItemList = itemProvider.Search(ItemSearch);
            if (ItemList.Count == 0)
                stockItem.ItemID = itemProvider.InsertItem(item);
            else
            {
                Item existItem = ItemList.FirstOrDefault();
                stockItem.ItemID = existItem.ID;
            }

            StockItemsSearchCriteria search = new StockItemsSearchCriteria()
            {
                ItemID = stockItem.ItemID,
                StockID = stockItem.StockID
            };

            if (stockItemsProvider.GetByItemIDAndStockID(search) == null)
            {
                stockItemsProvider.Insert(stockItem);
                return true;
            }
            else
                return false;
        }

        public Item GetByBarcode(string barCode)
        {
            ItemSearchCriteria ItemSearch = new ItemSearchCriteria();
            ItemSearch.Barcode = barCode;

            return itemProvider.Search(ItemSearch).FirstOrDefault();
        }

        public Item GetByPartNumber(string PartNumber)
        {
            return itemProvider.GetByPartNumber(PartNumber);
        }

        public override bool Update(Item updatedItem)
        {
            itemProvider.Update(updatedItem);
            return true;
        }

        public override bool Delete(int id)
        {
            throw new NotImplementedException();
        }

        public override Item GetByID(int id)
        {
            return itemProvider.GetByID(id);
        }

        public override List<Item> Search(ItemSearchCriteria SearchCriteria)
        {
            return itemProvider.Search(SearchCriteria).ToList();
        }

        public List<Item> UserSearch(ItemSearchCriteria search)
        {
            return itemProvider.UserSearch(search);
        }

        public List<Item> GetAll()
        {
            return itemProvider.GetAll();
        }
    }
}